package com.duyi.demo.component;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import javax.mail.internet.MimeMessage;
import java.util.HashMap;
import java.util.Map;

/**
 * @author ctx
 * @date 2020/2/15
 * @description
 */
@Component
public class MailComponent {

    @Autowired
    private JavaMailSender mailSender;

    public void send(){

            System.out.println("执行发送邮件逻辑");
            SimpleMailMessage mailMessage = new SimpleMailMessage();

            //发送规则：邮件要有主题
            mailMessage.setSubject("测试邮件");
            mailMessage.setText("雯雯邮件轰炸1.0");
            mailMessage.setTo("zhangyiwen789@qq.com");
            mailMessage.setFrom("948373513@qq.com");

            mailSender.send(mailMessage);

    }

    @Autowired
    private TemplateEngine templateEngine;

    public void send1(){
        System.out.println("执行send1发送逻辑");
        try {
            MimeMessage mailMessage = mailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(mailMessage,true);

            helper.setSubject("测试邮件2");
            //使用thymeleaf
            Context context = new Context();
            Map<String,Object> valueMap = new HashMap<>();
            valueMap.put("title","邮件正文标题");
            valueMap.put("content","邮件正文内容");

            context.setVariables(valueMap);
            String content = templateEngine.process("mail",context);
            helper.setText(content,true);

            helper.setTo("chentianxi1212@163.com");
            helper.setFrom("948373513@qq.com");

            //附件
//            FileSystemResource fileSystemResource = null;
//            helper.addAttachment("name",fileSystemResource);
            mailSender.send(mailMessage);
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
